import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
import readline from 'readline';

const prisma = new PrismaClient();

// 创建命令行输入接口
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// 封装问题询问函数
const askQuestion = (question: string): Promise<string> => {
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      resolve(answer);
    });
  });
};

// 创建隐藏密码输入（简单版本）
const askPassword = (question: string): Promise<string> => {
  return new Promise((resolve) => {
    process.stdout.write(question);
    process.stdin.setRawMode(true);
    process.stdin.resume();
    
    let password = '';
    process.stdin.on('data', (char: Buffer) => {
      const charStr = char.toString();
      
      if (charStr === '\r' || charStr === '\n') {
        process.stdin.setRawMode(false);
        process.stdin.pause();
        process.stdout.write('\n');
        resolve(password);
      } else if (charStr === '\u0003') { // Ctrl+C
        process.exit();
      } else if (charStr === '\u007f') { // Backspace
        if (password.length > 0) {
          password = password.slice(0, -1);
          process.stdout.write('\b \b');
        }
      } else {
        password += charStr;
        process.stdout.write('*');
      }
    });
  });
};

async function createInitialAdmin() {
  try {
    console.log('=== 创建初始管理员 ===\n');

    // 检查是否已有管理员
    const adminCount = await prisma.admin.count();
    if (adminCount > 0) {
      console.log('❌ 数据库中已存在管理员账户！');
      console.log(`当前管理员数量: ${adminCount}`);
      
      const forceCreate = await askQuestion('是否强制创建新的管理员？(y/N): ');
      if (forceCreate.toLowerCase() !== 'y' && forceCreate.toLowerCase() !== 'yes') {
        console.log('操作已取消。');
        return;
      }
    }

    // 获取用户输入
    const username = await askQuestion('请输入用户名: ');
    if (!username || username.trim() === '') {
      console.log('❌ 用户名不能为空！');
      return;
    }

    // 检查用户名是否已存在
    const existingAdmin = await prisma.admin.findUnique({
      where: { username: username.trim() }
    });

    if (existingAdmin) {
      console.log('❌ 用户名已存在！');
      return;
    }

    const password = await askPassword('请输入密码: ');
    if (!password || password.length < 6) {
      console.log('❌ 密码长度至少6位！');
      return;
    }

    const confirmPassword = await askPassword('请再次输入密码: ');
    if (password !== confirmPassword) {
      console.log('❌ 两次输入的密码不一致！');
      return;
    }

    const email = await askQuestion('请输入邮箱 (可选): ');
    const nickname = await askQuestion('请输入昵称 (可选): ');

    // 加密密码
    console.log('\n正在创建管理员...');
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建管理员
    const admin = await prisma.admin.create({
      data: {
        username: username.trim(),
        password: hashedPassword,
        email: email.trim() || null,
        nickname: nickname.trim() || null,
        role: 'admin',
        status: true
      }
    });

    console.log('✅ 管理员创建成功！');
    console.log(`ID: ${admin.id}`);
    console.log(`用户名: ${admin.username}`);
    console.log(`邮箱: ${admin.email || '未设置'}`);
    console.log(`昵称: ${admin.nickname || '未设置'}`);
    console.log(`创建时间: ${admin.createdAt}`);

  } catch (error) {
    console.error('❌ 创建管理员失败:', error);
    
    // 更详细的错误信息
    if (error instanceof Error) {
      if (error.message.includes('Unique constraint failed')) {
        console.log('错误原因: 用户名已存在');
      } else if (error.message.includes('connect')) {
        console.log('错误原因: 无法连接数据库，请检查数据库配置');
      } else {
        console.log('错误详情:', error.message);
      }
    }
  } finally {
    rl.close();
    await prisma.$disconnect();
  }
}

// 优雅处理程序退出
process.on('SIGINT', async () => {
  console.log('\n\n程序被中断');
  rl.close();
  await prisma.$disconnect();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  console.log('\n\n程序被终止');
  rl.close();
  await prisma.$disconnect();
  process.exit(0);
});

// 运行脚本
if (require.main === module) {
  createInitialAdmin();
}

export default createInitialAdmin;